import { defineStore } from 'pinia';
import { store } from '@/store';
import { login, phoneNumberApi, userInfoApi } from '@/api/login';
import { CacheEnum } from '@/enums/CacheEnum';
import { logManager } from '@/utils/log';
import { ThridTypeEnum } from '@/enums/LoginEnum';
import { IGetPhoneNumber, ILoginRes, UserInfoData } from '@/api/login/types';

export interface UserState {
  Token: string | null;
  /** token过期时间 */
  tokenExpireTime: number | null;
  userInfo: UserInfoData | null;
  /** 用户分享时会默认带上分享id */
  shareId: string;
  /** 审核消息数量 */
  auditMessageCount: number;
  /** 客服uuid */
  customerServiceUuid: string;
}

const createState = (): UserState => ({
  Token: uni.getStorageSync(CacheEnum.TOKEN),
  userInfo: uni.getStorageSync(CacheEnum.USERINFO),
  shareId: uni.getStorageSync(CacheEnum.SHAREID),
  auditMessageCount: 9,
  tokenExpireTime: uni.getStorageSync(CacheEnum.TOKEN_EXPIRE_TIME),
  customerServiceUuid: '100000000000000001',
});

export const useUserStore = defineStore({
  id: 'user',
  state: () => createState(),
  getters: {
    uuid: (state) => state.userInfo?.aiUserAccountBotVo?.uuid,
  },
  actions: {
    setAuditMessageCount(count: number) {
      this.auditMessageCount = count;
    },

    /** 登录
     * @description
     * @date 19/09/2023
     */
    async wxLogin(): Promise<boolean> {
      // #ifdef MP-WEIXIN
      try {
        if (this.Token && this.tokenExpireTime && this.tokenExpireTime > Date.now()) {
          return Promise.resolve(true);
        }
        const { code } = await wx.login();
        const res = await login({ code, thridType: ThridTypeEnum.MINIAPP })
        this.Token = res.token;
        // 设置token过期时间, 过期时间为24小时 - 5分钟
        this.tokenExpireTime = Date.now() + 24 * 60 * 60 * 1000 - 5 * 60 * 1000
        console.log('token过期时间', this.tokenExpireTime);
        console.log('now Date', Date.now());
        uni.setStorageSync(CacheEnum.TOKEN, res.token);
        uni.setStorageSync(CacheEnum.TOKEN_EXPIRE_TIME, this.tokenExpireTime);
        if (res.isBind) {
          await this.getUserInfo();
        }
        return true
      } catch (error) {
        console.log(error);
        logManager.error(error);
        return Promise.reject();
      }
      // #endif
      // #ifndef MP-WEIXIN
      return Promise.resolve(true);
      // #endif
    },

    /**
     * @description 获取用户信息
     * @date 16/10/2023
     */
    async getUserInfo() {
      const res = await userInfoApi();
      this.shareId = res.userShareId;
      this.userInfo = res;
      uni.setStorageSync(CacheEnum.USERINFO, res);
      uni.setStorageSync(CacheEnum.SHAREID, res.userShareId);
    },

    /**
     * 清除所有缓存
     */
    clearLocalAllStorage() {
      uni.clearStorageSync();
      this.$reset();
    },
  },
});
export function useUserStoreWithOut() {
  return useUserStore(store);
}
